package com.autoscript.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.autoscript.ISystemConstant;
import com.autoscript.vo.MenuJsonVo;
import com.autoscript.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dfhc.securitydb.service.SecurityDBClientService;
import com.dfhc.util.StringHelper;
import com.autoscript.vo.UserMenuVo;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户菜单表服务
 * @author lsb
 * @version 1.0.0
 * @date 2021-02-02
 */
@Service
public class UserMenuService {
	private static Logger logger=LoggerFactory.getLogger(UserMenuService.class);
	@Autowired
	private PublicService publicService;
	/**
	 * 表名
	 */
	private String TABLE_NAME="AS_USER_MENU";

	/**
	 * 统计记录数
	 * @param searchMap
	 * @return
	 */
	public long count(Map<String, Object> searchMap) {
		return SecurityDBClientService.getInstance().count(getDBSesion(), TABLE_NAME, searchMap);
	}

	/**
	 *  插入
	 * @param qrCodeType
	 * @throws Exception 
	 */
	public void insert(UserMenuVo userMenuVo) throws Exception {
		Map<String, Object> data;
		data = new HashMap<String,Object>();
		//获取序列id
		if(StringHelper.isEmpty(userMenuVo.getId())){
			data.put("ID",publicService.getIds(TABLE_NAME, 1)[0]);
		}
		if(!StringHelper.isEmpty(userMenuVo.getId())){
			data.put("ID",userMenuVo.getId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuId())){
			data.put("MENU_ID",userMenuVo.getMenuId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuCode())){
			data.put("MENU_CODE",userMenuVo.getMenuCode());
		}
		if(!StringHelper.isEmpty(userMenuVo.getUserId())){
			data.put("USER_ID",userMenuVo.getUserId());
		}
		int rowNum = SecurityDBClientService.getInstance().insert(getDBSesion(), TABLE_NAME, data);
		if(rowNum!=1) {
			logger.error("插入用户菜单表失败！数据为:"+data+",rowNum:"+rowNum);
			throw new Exception("插入用户菜单表失败！");
		}
	}
	
	/**
	 * 获取db会话
	 * @return
	 */
	private String getDBSesion() {
		return DBSessionService.getSingleInstance().getSession();
	}
	/**
	 * 更新用户菜单表
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public int update(UserMenuVo userMenuVo) throws Exception{
		Map<String, Object> searchMap;
		Map<String, Object> data;

		if(StringHelper.isEmpty(userMenuVo.getId()))
			throw new Exception("用户菜单表id为空!");
		searchMap = new HashMap<String,Object>();
		
		searchMap.put("ID",userMenuVo.getId());
		data = new HashMap<String,Object>();
		if(!StringHelper.isEmpty(userMenuVo.getId())){
			data.put("ID",userMenuVo.getId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuId())){
			data.put("MENU_ID",userMenuVo.getMenuId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuCode())){
			data.put("MENU_CODE",userMenuVo.getMenuCode());
		}
		if(!StringHelper.isEmpty(userMenuVo.getUserId())){
			data.put("USER_ID",userMenuVo.getUserId());
		}
		int rowNum = SecurityDBClientService.getInstance().update(getDBSesion(), TABLE_NAME, searchMap, data);
		if(rowNum<1) {
			logger.error("更新用户菜单表失败!数据为:searchMap:"+searchMap+",data:"+data+",rowNum:"+rowNum);
			throw new Exception("更新用户菜单表失败!");
		}
		return rowNum;
	}
	/**
	 * 删除用户菜单表
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public int delete(UserMenuVo userMenuVo) throws Exception{
		Map<String,Object> searchMap = new HashMap<String,Object>();
		if(!StringHelper.isEmpty(userMenuVo.getId())){
			searchMap.put("ID",userMenuVo.getId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuId())){
			searchMap.put("MENU_ID",userMenuVo.getMenuId());
		}
		if(!StringHelper.isEmpty(userMenuVo.getMenuCode())){
			searchMap.put("MENU_CODE",userMenuVo.getMenuCode());
		}
		if(!StringHelper.isEmpty(userMenuVo.getUserId())){
			searchMap.put("USER_ID",userMenuVo.getUserId());
		}
		int rowNum = SecurityDBClientService.getInstance().delete(getDBSesion(), TABLE_NAME, searchMap);
		if(rowNum<1) {
			logger.error("删除用户菜单表失败,参数为:"+searchMap+",rowNum:"+rowNum);
			throw new Exception("删除用户菜单表失败!");
		}
		return rowNum;		
	}

	/**
	 * 查询用户菜单表
	 * @param searchMap 查询条件
	 * @param pageNo 页号
	 * @param pageSize 页大小
	 * @return
	 */
	public List<Map> listPage(Map<String, Object> searchMap, int pageNo, int pageSize) {
		return SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap, pageNo, pageSize);
	}
	/**
	 * 查询用户菜单表
	 * @param searchMap 查询条件
	 * @return
	 */
	public List<Map> search(Map<String, Object> searchMap) {
		return SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap);
	}
	/**
	 * 根据id查询用户菜单表
	 * @param id id标识
	 * @return
	 */
	public Map getById(String id) throws Exception {
		if(StringHelper.isEmpty(id))
			throw new Exception("用户菜单表id为空!");
		Map<String,Object> searchMap = new HashMap<String,Object>();
		
		searchMap.put("ID",id);
		List<Map> resultList =  SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap);
 		if(resultList==null||resultList.size()==0){
 		  return null;
 		}else{
 		  return resultList.get(0);
 		}
	}

	/**
	 * 将用户拥有菜单转换为vue渲染菜单列表
	 * @return
	 * @throws Exception
	 */
	public List<MenuJsonVo> convertToMenuJsonVos(List<Map> allMenus, List<Map> userMenus) throws Exception{
		List<MenuJsonVo> retMenuJsonVos = new ArrayList<>();

		//循环转换菜单
		for(Map userMenu:userMenus) {
			//加载一级菜单
			String menuCode;
			menuCode = (String)userMenu.get("MENU_CODE");
			if(menuCode.length()==3) {
				//获取菜单项信息
				Map menuItem = getMenuItem((String) userMenu.get("MENU_ID"), allMenus);
				if (menuItem == null)
					throw new Exception("菜单：" + JSON.toJSONString(userMenu) + "没找到!");
				//转换为MeuJsonVo
				MenuJsonVo menuJsonVo = convertMenuJsonVo(menuItem);
				//查询下级菜单
				List<MenuJsonVo> childMenus = getChildMenus(allMenus, menuJsonVo);
				if (childMenus != null && childMenus.size() > 0) {
					menuJsonVo.setChildren(childMenus);
				}
				retMenuJsonVos.add(menuJsonVo);
			}
		}

		return retMenuJsonVos;
	}

	/**
	 * 查询下级菜单
	 * @param allMenus
	 * @param menuJsonVo
	 * @return
	 */
	private List<MenuJsonVo> getChildMenus(List<Map> allMenus, MenuJsonVo menuJsonVo) {
		List<MenuJsonVo> childs = new ArrayList<>();

		for(Map menu:allMenus){
			if(menuJsonVo.getMenuCode().equals(menu.get("PARENT_CODE"))){
				childs.add(convertMenuJsonVo(menu));
			}
		}
		return childs;
	}

	/**
	 * 转换为MenuJsonVo菜单
	 * @param menuItem
	 * @return
	 */
	private MenuJsonVo convertMenuJsonVo(Map menuItem) {

		MenuJsonVo menuJsonVo = new MenuJsonVo();
		menuJsonVo.setMenuCode((String)menuItem.get("MENU_CODE"));
		menuJsonVo.setMenuLink((String)menuItem.get("MENU_LINK"));
		menuJsonVo.setMenuName((String)menuItem.get("MENU_NAME"));
		menuJsonVo.setMenuOrder((String)menuItem.get("MENU_ORDER"));
		menuJsonVo.setParentCode((String)menuItem.get("PARENT_CODE"));
		return menuJsonVo;
		}

	/**
	 * 查询菜单项信息
	 * @param allMenus
	 * @return
	 */
	private Map getMenuItem(String id,List<Map> allMenus) {
		for(Map m:allMenus){
			if(id.equals(m.get("ID"))){
				return m;
			}
		}
		return null;
	}

	/**
	 * 授权普通用户菜单
	 * @param request
	 * @param newUserMap
	 */
	public void getGrantMenu(HttpServletRequest request, Map newUserMap) throws Exception {
		//循环插入非管理员菜单
		List<Map> allMenu = (List<Map>)ParameterCacheService.getSingleInstance().get(ISystemConstant.ALL_MENU);
		for(Map menuItem:allMenu){
			if(ISystemConstant.DICTIONARY_RM_YES_NOT_0.equals(menuItem.get("IS_ADMIN"))){
				UserMenuVo userMenuVo = new UserMenuVo();
				userMenuVo.setMenuCode((String)menuItem.get("MENU_CODE"));
				userMenuVo.setMenuId((String)menuItem.get("ID"));
				userMenuVo.setUserId((String)newUserMap.get("ID"));
				insert(userMenuVo);
			}
		}
	}
}
